package site.icesky.springboot.threadpool.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName: ThreadPoolConfig <br>
 * @Description: 线程池初始化 <br>
 * @Package: site.icesky.springboot.threadpool.config <br>
 * @author: suitianmou <br>
 * @Date: 2020/8/13-20:23 <br>
 * @version: 1.0 <br>
 * @see <br>
 * @since (从产品的哪一个版本此类被添加进来 ( 可选))<br>
 * 修改历史: <br>
 * 修改时间             修改人           版本变更           修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Configuration
public class ThreadPoolConfig {
    private static final Logger  logger = LoggerFactory.getLogger(ThreadPoolConfig.class);

    /* 线程池命名前缀 */
    @Value("${thread-pool.name-prefix}")
    private String namePrefix;

    /* 线程池最小数量 */
    @Value("${thread-pool.core-threads}")
    private int coreThreads;

    /* 线程池最大数量 */
    @Value("${thread-pool.max-threads}")
    private int maxThreads;

    /* 线程池活跃线程秒数 */
    @Value("${thread-pool.keep-alive-seconds}")
    private int keepAliveSeconds;

    /* 线程池队列容量 */
    @Value("${thread-pool.queue-capacity}")
    private int queueCapacity;

    @Bean("taskExector")
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        if( logger.isInfoEnabled()){
            logger.info("线程池启动初始化开始!");

            logger.info("线程池名称前缀：" + namePrefix);
            logger.info("线程池最小数量: " + coreThreads);
            logger.info("线程池最大数量：" + maxThreads);
            logger.info("线程活跃时间：" + keepAliveSeconds);
            logger.info("队列容量：" + queueCapacity);
        }

        // 设置核心线程数
        executor.setCorePoolSize(coreThreads);

        // 设置最大线程数
        executor.setMaxPoolSize(maxThreads);

        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);

        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(keepAliveSeconds);

        // 设置默认线程数
        executor.setThreadNamePrefix(namePrefix);

        // 设置拒绝策略
        executor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy());

        // 等待所有任务结束再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);

        return executor;
    }


}
